<!doctype html>
<html>
<head>
  <script src="./js/config.js"></script>
  <meta charset="utf-8">
  <title>License 管理（前后端分离）</title>
  <style>
    body{font-family:Arial,Helvetica,sans-serif;margin:40px; font-size:18px}
    .alert-bar{height:36px;line-height:36px;text-align:center;color:#fff;font-weight:bold}
    .alert-red{background:#e74c3c}.alert-orange{background:#f39c11}
    input{padding:4px}button{padding:6px 12px;margin-left:4px;font-size:16px}
    table{border-collapse:collapse;margin-top:10px;width:100%}
    th,td{border:1px solid #ccc;padding:8px 10px}
    .edit-txt,.edit-date{width:100%;box-sizing:border-box;border:1px solid #ccc;padding:4px 6px;height:32px}
    .nav{margin-bottom:20px}.nav a{margin-right:15px;font-weight:bold}
    h2,h3{font-size:26px;margin:0}
    /* 当前列表一行 左右分布 */
    .list-header{display:flex;justify-content:space-between;align-items:center;margin-top:20px}
  </style>
</head>
<body>

<div class="nav">
  <a href="index.html">首页</a>
  <a href="schedule.html">报警设置</a>
  <a href="log.html">报警日志</a>
  <a href="ding.html">钉钉设置</a>   <!-- 新增 -->
  <button class="bigscreen-btn" onclick="location.href='bigscreen.html'">📺 大屏</button>
</div>

<h2>Xinf_License 录入</h2>
<form id="addForm">
  <input name="customer" placeholder="客户名称" required>
  <input name="mac" placeholder="MAC 地址" required>
  <input name="expiry" type="date" required>
  <button>保存</button>
</form>

<div id="alertBox" class="alert-bar" style="display:none"></div>

<!-- 当前列表 + 按钮 -->
<div class="list-header">
  <h3>当前列表</h3>
  <div>
    <select id="robotSel" style="font-size:16px;padding:4px;"></select>
    <button onclick="testDing()">🔔 测试钉钉</button>
    <button onclick="downExcel()">📊 导出 Excel</button>
  </div>
</div>

<table id="list">
  <thead><tr><th>客户</th><th>MAC</th><th>到期日</th><th>状态</th><th>操作</th></tr></thead>
  <tbody></tbody>
</table>

<script>

async function apiGet(path){
  const r = await fetch(BASE + path);
  return r.json();
}
async function apiPost(path, body){
  const r = await fetch(BASE + path, {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify(body)
  });
  return r.text();   // 文本提示
}
async function apiPostForm(path, formData){
  const r = await fetch(BASE + path, {method:'POST', body: new URLSearchParams(formData)});
  return r.json();
}

/* 初始加载 */
async function load(){
  const data = await apiGet('/api/list');
  const tb = document.querySelector('#list tbody');
  tb.innerHTML = '';
  data.forEach(r=>{
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td><input class="edit-txt" data-key="customer" value="${r.customer}"></td>
      <td><input class="edit-txt" data-key="mac"      value="${r.mac}"></td>
      <td><input class="edit-date" type="date" data-key="expiry"
                value="${r.expiry}" onchange="saveRow(${r.id},this.closest('tr'))"></td>
      <td>${r.status}</td>
      <td><button onclick="delRow(${r.id})">删除</button></td>`;
    if (r.status.includes('已过期')) tr.style.color='#e74c3c';
    if (r.status.includes('即将过期')) tr.style.color='#f39c11';
    tb.appendChild(tr);
  });
}
/* 机器人下拉 */
async function loadRobots(){
  const list = await apiGet('/api/ding');
  const sel  = document.getElementById('robotSel');
  sel.innerHTML='';
  list.forEach(r=>{
    const opt = document.createElement('option');
    opt.value = r.id;
    opt.text  = r.name + (r.token?'':' - 无token');
    sel.appendChild(opt);
  });
  if(list.length===0) sel.innerHTML='<option value="">暂无机器人</option>';
}

/* 保存一行 */
async function saveRow(id, tr){
  const body={idx:id};
  tr.querySelectorAll('input[data-key]').forEach(i=> body[i.dataset.key]=i.value.trim());
  await apiPost('/api/replace', body);
  load();
}
/* 删除 */
async function delRow(id){
  if(!confirm('确定删除？')) return;
  await apiPost('/api/delete',{idx:id});
  load();
}
/* 新增 */
document.getElementById('addForm').onsubmit = async (e)=>{
  e.preventDefault();
  const fd = new FormData(e.target);
  const js = await apiPostForm('/api/add', fd);
  showAlert(js.alert);
  e.target.reset();
  load();
};

/* 测试钉钉 */
async function testDing(){
  const rid = document.getElementById('robotSel').value;
  if(!rid) return alert('请先添加机器人！');
  const msg = await apiPost('/api/test_ding', {robot_id: Number(rid)});
  alert(msg);
}
/* 导出 */
function downExcel(){
  location.href = BASE + '/api/export_excel';
}
/* 顶部状态条 */
function showAlert(msg){
  const box=document.getElementById('alertBox');
  if(msg){
    box.textContent=msg;
    box.className=msg.includes('已过期')?'alert-bar alert-red':'alert-bar alert-orange';
    box.style.display='block';
  }else box.style.display='none';
}

/* 页面入口 */
load();
loadRobots();
</script>
</body>
</html>